<?php
namespace app\api\controller\vppz;

use think\Db;
use think\Cache;


use \app\admin\model\vppz\FamilyMembers as FamilyMembersModel;
use \app\admin\model\vppz\AgeImageRelation as AgeImageRelationModel;
use \app\admin\model\vppz\HealthNote as HealthNoteModel;
use \app\admin\model\vppz\CommonDisease as CommonDiseaseModel;
use \app\admin\model\vppz\CommonAllergens as CommonAllergensModel;
use \app\admin\model\vppz\VipPackage as VipPackageModel;
use \app\admin\model\vppz\VipOrder as VipOrderModel;
use \app\admin\model\vppz\User as UserModel;

use \addons\vppz\library\Vpower;

class Familydoctor extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();

        $this->FamilyMembersModel = new FamilyMembersModel;
        $this->AgeImageRelationModel = new AgeImageRelationModel;
        $this->HealthNoteModel = new HealthNoteModel;
        $this->CommonDiseaseModel = new CommonDiseaseModel;
        $this->CommonAllergensModel = new CommonAllergensModel;
        $this->VipPackageModel = new VipPackageModel;
        $this->VipOrderModel = new VipOrderModel;
        $this->UserModel = new UserModel;
    }
    public function deleteUser(){
        $user_id = input('id','');
        $this->FamilyMembersModel->where([
            'id'=>$user_id
        ])->delete();
        $this->success('成功',[]);
    }
    public function createData(){
        $json = file_get_contents("php://input");
        $info = $this->FamilyMembersModel->where([
            'user_id'=>$this->_mine['id']
        ])->find();
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        $age = 0;
        $avator = 'https://banyetang.oss-cn-beijing.aliyuncs.com/xiaochengxu/avatar.jpg';
        $background = 'https://banyetang.oss-cn-beijing.aliyuncs.com/xiaochengxu/nancheng.jpeg';
        if(empty($data['birth']) === FALSE){
            $age = \Tools::calculateAge($data['birth']);
            //获取头像和背景图
            $agerelation = $this->AgeImageRelationModel->whereNull('deletetime')
                ->where(['sex'=>$data['gender']])
                ->order('min_age','asc')
                ->select();
            if(empty($agerelation) === FALSE){
                $avator = $agerelation[0]['avator_url'];
                $background = $agerelation[0]['background_url'];
                foreach ($agerelation as &$v){
                    if($v['min_age'] <= $age && $v['max_age'] > $age){
                        $avator = $v['avator_url'];
                        $background = $v['background_url'];
                        break;
                    }
                }
            }
        }
        $orderdata = array(
            'user_id'=>$this->_mine['id'],
            'name'=>$data['name'],
            'relation'=>$data['relation'],
            'gender'=>$data['gender'],
            'age'=>$age,
            'birth'=>$data['birth'],
            'avator'=>$avator,
            'background'=>$background,
            'updatetime'=>time(),
            'height'=>$data['height'],
            'weight'=>$data['weight'],
            'health_tips'=>$data['health_tips'],
            'blood_types'=>$data['blood_types'],
            'is_self'=>0
        );
        if(empty($data['avatarUrl']) === FALSE && empty($data['nickName']) === FALSE) {
            //更新用户信息
            $this->UserModel->where(['id' => $this->_mine['id']])->update(array(
                'updatetime' => time(),
                'nickname' => $data['name'],
                'mobile' => $data['phone'],
                'avatar' => $data['avatarUrl']
            ));
        }
        if(empty($info)){
            $orderdata['is_self'] = 1;
        }
        if(isset($data['id']) && $data['id'] > 0){
            $ret = $this->FamilyMembersModel->where([
                'id'=>$data['id']
            ])->update($orderdata);
            $id= $data['id'];
        }else {
            $ret = $this->FamilyMembersModel->save($orderdata);
            $id = $this->FamilyMembersModel->id;
        }
		if($ret){
            $datainfo = $this->FamilyMembersModel->where([
                'id'=>$id
            ])->find();
            $this->success('提交成功',$datainfo);
		}else{
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }
    //获取家人列表
    public function getFamilyData(){
        $mine = $this->_mine;
        $info = $this->FamilyMembersModel->where([
            'user_id'=>$mine['id']
        ])->whereNull('deletetime')->order('is_self','desc')->select();
        if(empty($info) === FALSE){
            foreach ($info as &$v){
                $v['short_name'] = \Tools::getshortname($v['name']);
                if($v['gender'] == 1){
                    $v['genderName'] = '男';
                }elseif ($v['gender'] == 2){
                    $v['genderName'] = '女';
                }else{
                    $v['genderName'] = '其他';
                }
                $v['bloodTypeName'] = $v['blood_types'].'型';
            }
        }
        $this->success('成功',$info);
    }
    public function createFamilyNoteData(){
        $json = file_get_contents("php://input");
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        $info = $this->HealthNoteModel->where([
            'family_id'=>$data['family_id'],
            'type'=>$data['type']
        ])->find();
        $content = array(
            'hasFamilyHistory'=>$data['hasFamilyHistory'],
            'selectedDiseases'=>$data['selectedDiseases'],
            'customDiseases'=>$data['customDiseases']
        );
        $resdata = array(
            'family_id'=>$data['family_id'],
            'type'=>$data['type'],
            'content'=>json_encode($content)
        );
        if(empty($info) === FALSE){
            $ret = $this->HealthNoteModel->where([
                'id'=>$info['id']
            ])->update($resdata);
            $id= $info['id'];
        }else {
            $ret = $this->HealthNoteModel->save($resdata);
            $id = $this->HealthNoteModel->id;
        }
		if($ret){
            $datainfo = $this->HealthNoteModel->where([
                'id'=>$id
            ])->find();
            $this->success('提交成功',$datainfo);
		}else{
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }
    public function createPersonlData(){
        $json = file_get_contents("php://input");
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        $info = $this->HealthNoteModel->where([
            'family_id'=>$data['family_id'],
            'type'=>$data['type']
        ])->find();
        $content = $data['personalData'];
        $resdata = array(
            'family_id'=>$data['family_id'],
            'type'=>$data['type'],
            'content'=>json_encode($content)
        );
        if(empty($info) === FALSE){
            $ret = $this->HealthNoteModel->where([
                'id'=>$info['id']
            ])->update($resdata);
            $id= $info['id'];
        }else {
            $ret = $this->HealthNoteModel->save($resdata);
            $id = $this->HealthNoteModel->id;
        }
		if($ret){
            $datainfo = $this->HealthNoteModel->where([
                'id'=>$id
            ])->find();
            $this->success('提交成功',$datainfo);
		}else{
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }
    public function createPastData(){
        $json = file_get_contents("php://input");
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        $info = $this->HealthNoteModel->where([
            'family_id'=>$data['family_id'],
            'type'=>$data['type']
        ])->find();
        $content = $data['pastData'];
        $resdata = array(
            'family_id'=>$data['family_id'],
            'type'=>$data['type'],
            'content'=>json_encode($content)
        );
        if(empty($info) === FALSE){
            $ret = $this->HealthNoteModel->where([
                'id'=>$info['id']
            ])->update($resdata);
            $id= $info['id'];
        }else {
            $ret = $this->HealthNoteModel->save($resdata);
            $id = $this->HealthNoteModel->id;
        }
		if($ret){
            $datainfo = $this->HealthNoteModel->where([
                'id'=>$id
            ])->find();
            $this->success('提交成功',$datainfo);
		}else{
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }
    //根据家人id  获取详情数据
    public function getHealthNote(){
        $family_id = input('family_id','');
        $type = input('type',0);
        $where = array(
            'family_id'=>$family_id
        );
        if($type > 0){
            $where['type'] = $type;
        }
        $info = $this->HealthNoteModel->where($where)->whereNull('deletetime')->select();
        $res = [
            'family'=>'',
            'personal'=>'',
            'past'=>''
        ];
        if(empty($info) === FALSE){
            foreach ($info as &$v) {
                if($v['type'] == 1){
                    $res['family'] = json_decode($v['content'],true);
                }elseif ($v['type'] == 2){
                    $res['personal'] = json_decode($v['content'],true);
                }else{
                    $res['past'] = json_decode($v['content'],true);
                }
            }
        }
        $this->success('成功',$res);
    }
    //获取常见疾病
    public function getCommonDisease(){
        $res = $this->CommonDiseaseModel->whereNull('deletetime')->select();
        $this->success('成功',$res);
    }
    //获取常见过敏源
    public function getCommonAllergens(){
        $res = $this->CommonAllergensModel->whereNull('deletetime')->select();
        $this->success('成功',$res);
    }
    //会员套餐
    public function getVipPackage(){
        $res = $this->VipPackageModel->whereNull('deletetime')->where(['is_show'=>1])->order('price','asc')->select();
        if(empty($res) === FALSE){
            foreach ($res as &$v){
                $v['duration'] = $v['duration'].'个月';
                //权益start
                $v['content'] = json_decode($v['content'],true);
            }
        }
        $this->success('成功',$res);
    }
    //下单
    public function placeorder(){
        $mine = $this->_mine;
        $json = file_get_contents("php://input");
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        //查询医生是否绑定用户
        $packageId = '';
        $package = $this->VipPackageModel->where(array(
            'id'=>$data['selectedPackageId']
        ))->whereNull('deletetime')->find();
        if(empty($package)){
            $this->error('套餐状态异常，请联系平台确认');
        }
        if($package['price'] !== $data['selectedPrice']){
            $this->error('套餐价格有误，请联系平台确认');
        }
        $orderdata = array(
            'user_id'=>$mine['id'],
            'openid'=>$mine['openid'],
            'order_no'=>uniqid('viporder_', true),
            'package_id'=>$data['selectedPackageId'],
            'package_price'=>$package['originalPrice'],
            'actual_amount'=>$package['price'],
            'content'=>$package['content'],
            'payment_method'=>1
        );
        $opera = array();
        $res=$this->VipOrderModel->save($orderdata);
		$order_id = $this->VipOrderModel->id;

		if($res){
            $pay_params = \addons\epay\library\Service::submitOrder([
                'amount'=>$orderdata['actual_amount'],
                'type'=>"wechat",
                'title'=>'家庭会员:'.$package['title'].'订单',
                'orderid'=>'VIP_'.$order_id,
                'notifyurl'=>$this->request->root(true) . '/addons/vppz/pay/notify/paytype/wechat',
                //'returnurl'=>"返回地址",// 小程序前端直接反馈无需返回地址页面
                'method'=>"miniapp",
                'openid'=>$orderdata['openid']
                //'auth_code'=>rand(1000,9999);
            ]);
            $this->success('下单成功',array(
                'order_id'=>$order_id,
                'pay_params'=>$pay_params
            ));
		}else{
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }
}
